<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab">
			<el-tab-pane label="基本信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>申请人员信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
										<template #label>
											<WtmLabelTooltip label="申请人员" tooltip="换班申请人员" />
										</template>
										<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :disabled="true" :prefill-person="prefillPerson" />
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="申请人员工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="申请人员姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>换班对象信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_SwapPersonId_FormItem" prop="Entity.SwapPersonId">
										<template #label>
											<WtmLabelTooltip label="换班对象" tooltip="换班对象人员" />
										</template>
										<WtmPersonSelector v-model="stateData.vmModel.Entity.SwapPersonId" :disabled="true" :prefill-person="prefillSwapPerson" />
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_SwapStaffNo_FormItem" prop="Entity.SwapStaffNo">
										<template #label>
											<WtmLabelTooltip label="换班人工号" tooltip="换班对象人员工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.SwapStaffNo" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_SwapName_FormItem" prop="Entity.SwapName">
										<template #label>
											<WtmLabelTooltip label="换班人姓名" tooltip="换班对象人员姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.SwapName" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_SwapShiftInfo_FormItem" prop="Entity.SwapShiftInfo">
										<template #label>
											<WtmLabelTooltip label="换班对方排班记录" tooltip="换班对方的排班记录" />
										</template>
										<el-input v-model="swapShiftDisplayText" disabled clearable class="width100" placeholder="暂无排班记录"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>换班信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StartTime_FormItem" prop="Entity.StartTime">
										<template #label>
											<WtmLabelTooltip label="换班时间" tooltip="换班时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.StartTime" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
								<!-- <el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_EndTime_FormItem" prop="Entity.EndTime">
										<template #label>
											<WtmLabelTooltip label="结束时间" tooltip="换班时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.EndTime" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col> -->
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Reason_FormItem" prop="Entity.Reason">
										<template #label>
											<WtmLabelTooltip label="事由" tooltip="换班事由" />
										</template>
										<el-input
											v-model="stateData.vmModel.Entity.Reason"
											disabled
											clearable
											class="width100"
											type="textarea"
											:rows="2"
											placeholder="请输入换班事由"
										></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>
							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :auth="false" :disabled="true" />
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>
			<el-tab-pane label="审批信息" key="审批信息">
				<WtmWorkflowTimeline entityType="HengTong.Model.Db.Bill.SysDailyShiftSwapRequestBill" :entityId="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, type ComponentInternalInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { SysDailyShiftSwapRequestBillApi as api } from '/@/views/daily/sysdailyshiftswaprequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysDailyShiftSwapRequestBillVm } from '/@/views/daily/sysdailyshiftswaprequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import ApproveReasonDialog from '/@/components/approveReason/index.vue';
import { SysAttendanceRecordApi as attendanceApi } from '/@/views/hr/sysattendancerecord/api';

/**
 * ===== 常量定义区域 =====
 * 统一管理业务常量，便于维护和复用
 */

/** 单据状态枚举 */
const BILL_STATUS = {
	DRAFT: '草稿', // 草稿状态，可编辑
	FORMAL: '正文', // 正式状态，不可编辑
} as const;

/** 工作流状态枚举 */
const WORKFLOW_STATUS = {
	PENDING: '待提交', // 初始状态，等待提交
	SUBMITTING: '提交中', // 正在提交流程
	IN_AUDIT: '审核中', // 审批流程中
	COMPLETED: '已完成', // 流程完成
	CANCELLED: '已取消', // 流程取消
} as const;

/**
 * ===== 下拉选项配置 =====
 * 用于表单的选项数据
 */

/** 单据状态下拉选项 */
const BILL_STATUS_OPTIONS = [
	{ value: BILL_STATUS.DRAFT, label: BILL_STATUS.DRAFT },
	{ value: BILL_STATUS.FORMAL, label: BILL_STATUS.FORMAL },
] as const;

/** 工作流状态下拉选项 */
const WORKFLOW_STATUS_OPTIONS = [
	{ value: WORKFLOW_STATUS.PENDING, label: WORKFLOW_STATUS.PENDING },
	{ value: WORKFLOW_STATUS.SUBMITTING, label: WORKFLOW_STATUS.SUBMITTING },
	{ value: WORKFLOW_STATUS.IN_AUDIT, label: WORKFLOW_STATUS.IN_AUDIT },
	{ value: WORKFLOW_STATUS.COMPLETED, label: WORKFLOW_STATUS.COMPLETED },
	{ value: WORKFLOW_STATUS.CANCELLED, label: WORKFLOW_STATUS.CANCELLED },
] as const;

/**
 * ===== 按钮文本常量 =====
 */
const BUTTON_TEXTS = {
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

/**
 * ===== 审批动作常量 =====
 */
const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

/**
 * ===== API接口路径常量 =====
 */
const API_ENDPOINTS = {
	GROUPS: '/api/SysDailyShiftSwapRequestBill/GetSysGroups',
} as const;

/**
 * ===== 标签页名称常量 =====
 */
const TAB_NAMES = {
	MAIN: 'main',
	APPROVAL: '审批信息',
} as const;

/**
 * ===== 组件实例和基础配置 =====
 */

/** 组件实例，用于访问组件上下文 */
const ci = getCurrentInstance() as ComponentInternalInstance;

/** 页面加载状态控制 */
const loading = ref(false);

/** 表单组件引用 */
const formRef = ref();

/** 当前活动的标签页 */
const activeTab = ref(TAB_NAMES.MAIN);

/**
 * ===== 响应式状态数据 =====
 */

/** 表单数据状态 */
const stateData = reactive<IViewModel<ISysDailyShiftSwapRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			StartTime: null,
			EndTime: null,
			Reason: null,
			SwapPersonId: null,
			SwapStaffNo: null,
			SwapName: null,
			SwapShiftId: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		},
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysGroups: [] as any[], // 所有部门组织数据
});

/**
 * ===== 计算属性 =====
 * 根据响应式数据动态计算衍生值
 */

/** 是否处于审批状态 */
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);

/** 是否可以审批 - 需要审批权限且处于审批状态 */
const canApprove = computed(() => isInAudit.value && !!stateData.vmModel.IsMyApprove);

/** 申请人员回显数据 - 用于人员选择器的数据回显 */
const prefillPerson = computed(() => {
	const entity = stateData.vmModel.Entity;
	if (entity.PersonId && entity.Name && entity.StaffNo) {
		return {
			ID: entity.PersonId,
			Name: entity.Name,
			StaffNo: entity.StaffNo,
		};
	}
	return null;
});

/** 换班对象回显数据 - 用于换班对象选择器的数据回显 */
const prefillSwapPerson = computed(() => {
	const entity = stateData.vmModel.Entity;
	if (entity.SwapPersonId && entity.SwapName && entity.SwapStaffNo) {
		return {
			ID: entity.SwapPersonId,
			Name: entity.SwapName,
			StaffNo: entity.SwapStaffNo,
		};
	}
	return null;
});

/** 换班排班记录显示文本 */
const swapShiftDisplayText = ref<string>('');

/**
 * ===== 工具函数 =====
 */

/** 统一的成功处理函数 - 处理操作成功后的通用逻辑 */
const handleSuccess = () => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '操作成功');
	emit('refresh'); // 触发父组件刷新数据
	closeDialog(); // 关闭对话框
	loading.value = false;
};

/** 统一的错误处理函数 - 处理API调用失败等错误情况 */
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

/** 公共的审批处理函数 - 处理审批操作的通用逻辑 */
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api().approve(stateData.vmModel, '').then(handleSuccess).catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

/**
 * ===== 用户操作函数 =====
 */

/** 关闭对话框 */
const onClose = () => {
	closeDialog();
};

/** 审批同意 */
const onAgree = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};

/** 审批拒绝 */
const onDeny = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

/**
 * ===== 页面初始化函数 =====
 */

/** 初始化页面数据 - 从路由参数或传入数据中获取实体ID */
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

/** 加载页面数据 - 并行获取部门数据和实体数据 */
const loadPageData = async () => {
	const [groups, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false), // 获取部门列表
		api().get(stateData.vmModel.Entity.ID ?? ''), // 获取实体详情
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (entityData.status === 'fulfilled') {
		other.setValue(stateData.vmModel, entityData.value);
		// 加载排班记录显示信息
		await loadSwapShiftDisplayText();
	}
};

/** 加载换班排班记录显示文本 */
const loadSwapShiftDisplayText = async () => {
	const swapShiftId = stateData.vmModel.Entity.SwapShiftId;

	if (!swapShiftId) {
		swapShiftDisplayText.value = '';
		return;
	}

	try {
		const response = await attendanceApi().get(swapShiftId);
		if (response) {
			const vmData = response as any;
			const record = vmData.Entity || vmData;
			const shiftDate = record.ShiftDate || '';
			const shiftName =
				record.AttendanceShiftGroup?.Name ||
				record.AttendanceShift?.Name ||
				record.AttendanceShiftGroupName ||
				record.ShiftName ||
				record.ShiftInfo ||
				'未知班次';
			swapShiftDisplayText.value = shiftDate && shiftName ? `${shiftDate} - ${shiftName}` : swapShiftId;
		} else {
			swapShiftDisplayText.value = swapShiftId;
		}
	} catch (error) {
		console.error('查询排班记录详情失败:', error);
		swapShiftDisplayText.value = swapShiftId;
	}
};

/**
 * ===== 生命周期钩子 =====
 */

/** 组件挂载时执行 - 初始化页面数据 */
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons(); // 设置头部按钮
		});
	}
});

/**
 * ===== 组件通信 =====
 */

/** 定义子组件向父组件传值/事件 */
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

/** 关闭弹窗 */
const closeDialog = () => {
	emit('closeDialog');
};

/** 设置对话框头部按钮 - 根据当前状态动态配置可用按钮 */
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: canApprove.value && isInAudit.value,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: canApprove.value && isInAudit.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
